package main;

import com.alibaba.fastjson.JSONObject;
import constant.DefaultConfig;
import mode.Mode;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.yaml.snakeyaml.Yaml;
import util.CommonUtils;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    private static Map<String, Double> resultMap = new HashMap<>();
    private static String title;
    private static double base;

    public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, AWTException {
        if (!SystemTray.isSupported()) {
            CommonUtils.logError("你的系统不支持调用通知");
            return;
        }
        Map<String, Object> config = new Yaml().load(FileUtils.openInputStream(new File("config.yml")));
        List<String> fund = (List<String>) config.get("fund");
        if (fund == null || fund.size() == 0) {
            fund = DefaultConfig.FUND;
        }
        final String mode = (String) config.getOrDefault("mode", DefaultConfig.MODE);
        final Object baseValue = config.getOrDefault("base", DefaultConfig.BASE);
        title = (String) config.getOrDefault("title", DefaultConfig.TITLE);
        base = baseValue instanceof Integer ? ((Integer) baseValue).doubleValue() : (double) baseValue;
        analyse(fund);
        Mode modeStrategy = (Mode) Class.forName("mode." + mode.substring(0, 1).toUpperCase() + mode.substring(1) + Mode.class.getSimpleName()).newInstance();
        String notification = modeStrategy.formatNotification(resultMap);
        if (StringUtils.isBlank(notification)) {
            return;
        }
        sendNotification(notification);
        System.exit(0);
    }

    private static void analyse(List<String> fund) {
        fund.stream().forEach(fundCode -> {
            JSONObject jsonObject = null;
            try {
                jsonObject = CommonUtils.crawl("http://fundgz.1234567.com.cn/js/" + fundCode + ".js?rt=" + System.currentTimeMillis(), "utf-8");
            } catch (IOException e) {
                e.printStackTrace();
            }
            final Double gszzl = jsonObject.getDouble("gszzl");
            final String name = jsonObject.getString("name");
            if (gszzl > base || gszzl < -base) {
                resultMap.put(name, gszzl);
            }
        });
    }

    private static void sendNotification(String collect) throws AWTException {
        SystemTray tray = SystemTray.getSystemTray();
        Image image = Toolkit.getDefaultToolkit().createImage("icon.png");
        TrayIcon trayIcon = new TrayIcon(image, title);
        tray.add(trayIcon);
        trayIcon.displayMessage(title, collect, TrayIcon.MessageType.WARNING);
    }
}
